package com.study.controller;

import com.study.common.ResultJson;
import com.study.pojo.Book;
import com.study.pojo.User;
import com.study.service.BookService;
import com.study.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * 登陆注册控制器
 * @Author Miss kun
 * @Date 2020/10/10 17:33
 * @Version 1.0
 */

@Controller
@RequestMapping("/login")
public class LoginRegisterController {


    @Autowired
    private UserService userService;
    @Autowired
    private BookService bookService;

    /**
     * 处理注册
     * @return
     */
    @RequestMapping("/doRegister")
    public String doRegister(@RequestParam("afterPassword") String password, @RequestParam("phone") String phone, @RequestParam("qq") String qq){
        User user = new User(password,phone,qq);
        userService.addUser(user);
        return "login";
    }

    /**
     * 处理登陆请求
     */
    @RequestMapping("/doLogin")
    @ResponseBody
    public ResultJson doLogin(@RequestParam("phone") String phone, @RequestParam("password") String password) throws ServletException, IOException {
        User user = userService.findByPhone(phone);
        String msg = "0";
        if (user == null){
            //没有该用户，请注册/账户错误"
            msg = "1";
        }else if(user != null){
            //判断密码是否正确
            if(!user.getPassword().equals(password)){
                //密码错误
                msg = "2";
            }
        }
        return ResultJson.ok(msg);
    }

    @RequestMapping("/sendLogin")
    public String doLogin(HttpSession session , String phone, String password, Model model) {
        User user = userService.findByPhone(phone);
        //获取随机20本图书显示到前端页面
        List<Book> books = bookService.getBooks();
        //获取根据类别分类的排行榜
        List<Book> rankBooks = bookService.getBookByRankList();
        model.addAttribute("books",books);
        model.addAttribute("rankBooks",rankBooks);
        if (phone == null || password == null){
            return "index";
        }else {
            session.setAttribute("user",user);
            return "index";
        }
    }

    /**
     *判断用户是否注册,并返回json数据
     */
    @RequestMapping("/isRegister")
    @ResponseBody
    public ResultJson isRegister(@RequestParam("phone") String phone){
        String msg = "";
        User user = userService.findByPhone(phone);
        if (user == null){
            msg = "true";
        }else {
            msg = "false";
        }

        return ResultJson.ok(msg);
    }
}
